<template>
  <div>
    <el-card>
      <div slot="header">
        <span>{{typeName}}角色</span>
      </div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" label-position="left">
        <el-form-item label="角色名称:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请填写"></el-input>
        </el-form-item>
        <el-form-item label="归属机构:" prop="officeId" :rules="{required: true, message: '请选择归属机构'}">
          <el-cascader
            expand-trigger="hover"
            :props="officeProps"
            :options="officeData"
            v-model="officeValue"
            @change="handleChange"
            change-on-select
            placeholder="请选择">
          </el-cascader>
        </el-form-item>
        <el-form-item label="功能权限:" prop="menuIds">
          <el-tree
            v-loading="treeLoading"
            :data="menuTreeData"
            :props="menuTreeProps"
            :default-checked-keys="menuIdList"
            ref="menuTreeRef"
            show-checkbox
            node-key="id">
          </el-tree>
        </el-form-item>
        <!--<el-form-item label="是否启用:" prop="useable" :rules="{required: true, message: '请选择是否启用'}">-->
          <!--<el-switch v-model="ruleForm.useable" active-color="#13ce66"></el-switch>-->
        <!--</el-form-item>-->
        <el-form-item label-width="0">
          <el-button class="white-btn" size="small" @click="onCancel">取消</el-button>
          <el-button class="green-btn" size="small" @click="submitForm('ruleForm')">确定</el-button>
          <span>（<span style="color: red;">* </span>为必填项）</span>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import {getSysRoleInfo, addRole, updateRoleInfo } from '@/api/sysSettings/role'
import {getSysOfficeTree} from '@/api/sysSettings/company'
import {getMenuTree} from '@/api/sysSettings/menu'
import { Message } from 'element-ui'

export default {
  name: 'info',
  data () {
    return {
      treeLoading: false, // 菜单树加载中
      id: this.$route.params.id, // 路由参数--id
      type: this.$route.params.type, // 路由参数--type
      typeName: '', // 路由名称
      // 表单数据
      ruleForm: {
        name: '', // 姓名
        officeId: '', // 归属机构
        menuIds: '' // 功能权限的ids
        // useable: true // 是否启用
      },
      // 表单验证规则
      rules: {
        name: [{required: true, message: '请填写姓名', trigger: 'blur'}]
      },
      // 级联选择器配置项
      officeProps: {
        value: 'id',
        label: 'name',
        children: 'childList'
      },
      officeData: [], // 归属机构数据
      officeValue: [], // 归属机构默认值
      menuTreeData: [], // 功能权限菜单树数据
      // 功能权限菜单树配置项
      menuTreeProps: {
        id: 'id',
        label: 'name',
        children: 'children',
        disabled: 'disable'
      },
      menuIdList: [] // 功能权限菜单已选择的id
    }
  },
  mounted () {
    if (this.type === 'add') {
      this.typeName = '新增'
    } else if (this.type === 'update') {
      this.typeName = '修改'
      this.getUserInfo(this.id)
    }
    this.getOfficeTree()
    this.getMenuTree()
  },
  methods: {
    // 获取用户信息
    getUserInfo (id) {
      let param = {
        id: id
      }
      getSysRoleInfo(param).then(response => {
        let data = response.object
        this.officeValue = data.officeIdList || []
        this.menuIdList = data.menuIdList
        this.ruleForm = {
          id: data.id,
          name: data.name,
          officeId: data.officeId,
          menuIds: data.menuIdList.join(',')
        }
      }).catch(error => {
        Message({
          message: error.message,
          type: 'error'
        })
      })
    },
    // 获取机构树列表
    getOfficeTree () {
      this.treeLoading = true
      let param = {}
      getSysOfficeTree(param).then(response => {
        this.treeLoading = false
        let data = response.object.list
        this.officeData = this.handleResponseValue(data)
      }).catch(error => {

      }).finally(() => {
        this.treeLoading = false
      })
    },
    // 处理返回值数组中为空的属性
    handleResponseValue (array) {
      array.forEach(item => {
        if (item.childList && item.childList.length > 0) {
          this.handleResponseValue(item.childList)
        } else {
          delete item.childList
        }
      })
      return array
    },
    // 获取菜单树列表
    getMenuTree () {
      let param = {}
      getMenuTree(param).then(response => {
        let data = response.object
        this.menuTreeData = data
      })
    },
    // 选择归属机构
    handleChange (val) {
      this.ruleForm.officeId = val[val.length - 1]
    },
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗?', '系统提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: ''
          }).then(() => {
            let menuIdList = this.$refs.menuTreeRef.getCheckedKeys()
            let menuNodes = this.$refs.menuTreeRef.getCheckedNodes()
            // 填充父级id
            for (let i = 0, len = menuNodes.length; i < len; i++) {
              if (menuIdList.indexOf(menuNodes[i].parentId) === -1 && menuNodes[i].parentId !== '0') {
                menuIdList.push(menuNodes[i].parentId)
              }
            }
            this.ruleForm.menuIds = menuIdList.join(',')
            if (this.type === 'add') {
              addRole(this.ruleForm).then(res => {
                this.$message({
                  type: 'success',
                  message:res.message ,
                })
                this.$router.push('/system/role')
              })
            } else if (this.type === 'update') {
              updateRoleInfo(this.ruleForm).then(res => {
                this.$message({
                  type: 'success',
                  message:res.message ,
                })
                this.$router.push('/system/role')
              })
            }
          }).catch(() => {})
        } else {
          Message({
            message: '提交失败',
            type: 'error'
          })
          return false
        }
      })
    },
    // 取消按钮
    onCancel () {
      this.$router.push('/system/role')
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-input, .el-select, .el-cascader, .el-switch, .el-tree { width: 300px; }
  @import 'src/styles/settings.scss';
</style>
